package com.starsky.common.framework.validator;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * http工具类
 */
@Service
public class HttpClientUtils {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * get请求
     *
     * @param url：访问URL
     * @param resType：返回结果
     * @return
     */
    public <T> T sendGet(String url, Class<T> resType) throws Exception {
        HttpHeaders headers = new HttpHeaders();
//		headers.add("x-access-token", LowerHairHttpClient.API_TOKEN);
        HttpEntity<String> reqEntity = new HttpEntity(headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, reqEntity, resType);
        return response.getBody();
    }

    /**
     * post请求
     *
     * @param url：访问URL
     * @param param:参数
     * @param resType：返回结果
     * @return
     */
    public <T> T sendPost(String url, Class<T> resType, Object param) throws Exception {
        HttpHeaders headers = new HttpHeaders();
//		headers.add("x-access-token", LowerHairHttpClient.API_TOKEN);
        HttpEntity<String> reqEntity = new HttpEntity(param, headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, reqEntity, resType);
        return response.getBody();
    }

    /**
     * post请求
     *
     * @param url：访问URL
     * @param param:参数
     * @param resType：返回结果
     * @return
     */
    public <T> T sendPost(String url, Class<T> resType, JSONObject param) throws Exception {
        HttpHeaders headers = new HttpHeaders();
//		headers.add("x-access-token", LowerHairHttpClient.API_TOKEN);
        HttpEntity<String> reqEntity = new HttpEntity(param, headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, reqEntity, resType);
        return response.getBody();
    }

}
